package ru.arriah.servicedesk.web.dispatcher.action;

import java.io.IOException;
import java.util.Collection;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.arriah.common.web.action.ActionMapping;
import ru.arriah.common.web.action.DumbAction;
import ru.arriah.servicedesk.bean.ClientBean;
import ru.arriah.servicedesk.bean.IntWrapper;
import ru.arriah.servicedesk.ejb.ClientManagerLocalHome;
import ru.arriah.servicedesk.ejb.ClientManagerLocalObject;
import ru.arriah.servicedesk.help.Utils;
import ru.arriah.servicedesk.web.commonaction.exception.InternalException;


public class ListClientsAction extends DumbAction {
  protected ClientManagerLocalHome clientManagerHome;

  public ListClientsAction() throws NamingException {
    super();

    clientManagerHome = 
      Utils.getClientManagerHomeInterface();
  }
  
  /* constructor for runtime objects */
  public ListClientsAction(
     ClientManagerLocalHome clientManagerHome
  ) {
     super();
     this.clientManagerHome = clientManagerHome;       
  }

  
  public String execute(ActionMapping actionMapping,
    HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {
    try {
      int page = idVal(request.getParameter("page"));
      int itemsPerPage = Integer.parseInt(config.getProperty("ITEMS_PER_PAGE"));
      IntWrapper records = new IntWrapper(0);

      String order = request.getParameter("order");
      String orderBy = request.getParameter("orderBy");
      order = (order == null) ? "" : order;                
      orderBy = (orderBy == null) ? "" : orderBy;
      
      ClientManagerLocalObject clientManager = clientManagerHome.create();
      
      Collection<ClientBean> clientsList = clientManager.selectClients(
        orderBy, 
        order,
        page,
        itemsPerPage,
        records
      );
      
      clientManager.remove();
      
      this.pageNavigationToRequest(
        page,          
        records.getValue(), 
        "operatorui?_action=listClients&orderBy="+orderBy+"&order="+order+"&page=",
        request
      );

      request.setAttribute("order", (order.equals("ASC") ? "DESC" : "ASC"));
      request.setAttribute("clientsList", clientsList);
      return actionMapping.getSuccessTarget();
    } catch (Exception e) {
      handleException(e, "execute");
      throw new InternalException("ErrorMessage.internal");
    }
  }
}